package cn.com.gridinfo.sooc.core.my.course.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.course.adapter.SCCourseAdapter;
import cn.com.gridinfo.sooc.core.my.course.bean.SCCourse;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 我的课程（已收藏)
 * Created by Administrator on 2015/12/9.
 */
public class YscFragment extends BaseSoocFragment {
    View view;
    @InjectView(R.id.listView)
    UltimateRecyclerView shoucang_recyclerView;

    private MyDao dao;//我的 dao
    SCCourseAdapter scCourseAdapter;//已收藏课程适配器
    LinearLayoutManager linearLayoutManager;//列表管理器

    int pageNo = 1;
    int pageSize = 10;
    int maxLastPositon;//数据最后位置
    int positionNo;//要删除的课程

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.my_course_ysc_fragment_list, null);
        ButterKnife.inject(this, view);
        dao = new MyDao(this);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        shoucang_recyclerView.setLayoutManager(linearLayoutManager);

        return view;
    }

    public static YscFragment newInstance(String info) {
        return new YscFragment();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (scCourseAdapter == null) {
            pageNo = 1;
            dao.mySCCourse(pageNo, CodeConst.SCCOURSE_FIRST);
            linearLayoutManager.scrollToPosition(0);
        }

        else {
            pageNo = 1;
            dao.mySCCourse(pageNo, CodeConst.SCCOURSE_PUSHDOWN);
            linearLayoutManager.scrollToPosition(0);
        }
    }

    //    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        if(isVisibleToUser && isResumed()){
//            dao.mySCCourse(pageNo, CodeConst.SCCOURSE_FIRST);
//        }
//        super.setUserVisibleHint(isVisibleToUser);
//    }
    @Override
    public void onRequestSuccess(int requestCode) {

        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    //课程首次请求
                    case CodeConst.SCCOURSE_FIRST:
                        initCourseList();
                        if (dao.getScCourseList() != null && !dao.getScCourseList().isEmpty()) {
                            shoucang_recyclerView.hideEmptyView();
                        } else {
                            //无数据处理
                            shoucang_recyclerView.showEmptyView();
                        }
                        break;
                    case CodeConst.SCCOURSE_PUSHDOWN:
                        shoucang_recyclerView.setRefreshing(false);
                        if (dao.getScCourseList() != null && !dao.getScCourseList().isEmpty()) {
                            shoucang_recyclerView.hideEmptyView();
                        } else {
                            //无数据处理
                            shoucang_recyclerView.showEmptyView();
                        }
                        //刷新数据
                        scCourseAdapter.refresh(dao.getScCourseList());
                        if (dao.getScCourseList().size() > (pageSize - 1))
                            //数据大于每页显示的条数，
                            scCourseAdapter.loadMoreDataView();
                        else {
                            //数据小于当前页的话则不显示加载更多
                            scCourseAdapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);

                        }
                        break;
                    //课程翻页才做
                    case CodeConst.SCCOURSE_PULLUP:
                        if (dao.getScCourseList() != null && !dao.getScCourseList().isEmpty()) {
                            //加载更多
                            scCourseAdapter.loadmore(dao.getScCourseList());
                        } else {
                            //无数据则不显示下一页
                            scCourseAdapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                    case CodeConst.DELETECOURSE://删除已收藏的课程
                        MessageUtils.showRightImageShortToast(getActivity(), "删除成功");
                        scCourseAdapter.delete(positionNo);
                        //判断是否数据没有更多了 有更多,删除数据当前页不满 pageSize, 则刷新加载当前页,没有更多数据,则不去加载
                        if(scCourseAdapter.getIsLoadMore()) {
                            if (scCourseAdapter.getAdapterItemCount() < pageSize) {
                                //下拉刷新  账户明细数据
                                pageNo = 1;//首页
                                dao.mySCCourse(pageNo, CodeConst.SCCOURSE_PUSHDOWN);
                                linearLayoutManager.scrollToPosition(0);
                            }
                        }
                        break;

                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.statusCode);
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "请求数据异常");

        }
    }

    /**
     * 初始化 list 数据 分页
     */
    private void initCourseList() {
        scCourseAdapter = new SCCourseAdapter(dao.getScCourseList(), getActivity());
        shoucang_recyclerView.setAdapter(scCourseAdapter);
        shoucang_recyclerView.enableLoadmore();
        shoucang_recyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新  账户明细数据
                pageNo = 1;//首页
                dao.mySCCourse(pageNo, CodeConst.SCCOURSE_PUSHDOWN);
                linearLayoutManager.scrollToPosition(0);
            }
        });
        shoucang_recyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    dao.mySCCourse(++pageNo, CodeConst.SCCOURSE_PULLUP);
                } else {
                    scCourseAdapter.loadNoDataView();
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
        });

        //适配器单项点击事件 点击左滑后的删除按钮
        scCourseAdapter.setOnItemLongClickListener(new SCCourseAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, final SCCourse scCourse, int position) {
                positionNo = position;
                new MaterialDialog.Builder(getActivity())
                        .items(R.array.del_course)
                        .backgroundColor(getResources().getColor(R.color.white))
                        .contentColor(getResources().getColor(R.color.color_tv333))
                        .contentGravity(GravityEnum.CENTER)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                //取消收藏
                                dao.deleteScCourse(scCourse.getKcid());
                            }
                        })
                        .show();
            }
        });
        scCourseAdapter.setnOnItemClickListener(new SCCourseAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, SCCourse scCourse, int position) {
                Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                intent.putExtra("kcid", scCourse.getKcid());
                intent.putExtra("kcfm",scCourse.getKcfm());
                startActivityForResult(intent, 123);//点击取消收藏后刷新
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 123://进入课程页面，点击取消收藏后
                if (resultCode == Activity.RESULT_OK) {
                    dao.mySCCourse(pageNo, CodeConst.SCCOURSE_PUSHDOWN);
                }
                break;

        }
    }
}
